package com.wing.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {

    // Rsa 公钥MII
    public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
    // Rsa 私钥MII
    public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJwu3pol9aZGJ37wK6Ku/1mLyxV+FIn6lSQvt0L4zXJz57rOv49CPyxuXaNXlkGEXhXCggdbMUujE0pKLO6RQ3O6YmLUrCGOZsBI3YRUEpSEnCbHjbah7D1YKdlgT379P7EXzsOKJ7e5Cb7txhUKm+Wmqd/3MwEHQmz3NiM4+0/jAgMBAAECgYBZWcMF4xOPBXGRAGumTYFORFhxukiby1zJb/bi/J3kjYST7bXPinHDxHwTd4dBgi2lOzrSZIxmHixqAteDwF0aki+6e7Aosfr807z4eDXR/9k7mTpZkhA1srXD13GLZ55q6e+XCmENC5JrJqzOw8C4fadangBheogbRnhhgSdO6QJBAM40kkaHPaIdopyONCOc6Lg9oNa/iCA8FrV04AKdgtQRAxnZWrNMprCL4mTu2hQ48NcTdB5sNJt4eWHuYKoqKl0CQQDB5fdsgxmB+gr3ZefNcFnGygosmtgAJl8cKn/qfdkOq7BU43dClhu28v8mzHItGjPyQQy3rLnlvt0+t9BCBj8/AkEAhsHKejb1q1VsqJ0yK7fmSklULCNdRZufR5SKtIrVLdu0SBdIc/Z61NOF72o8sIyJsDSxZRRXyOaRhNNw7qPBrQJAVJkzlOK2VGF2O2747kegw/0O51s/9wDG6pEYcoUqGR6Ltt3wANthiDcJYDI/drJCC+aZ1+HC0hyuh1jHwqbbHQJABZTYE8/HWCbmraqK+TMdpr/h/duw0gz26Ry8Wox+DGDoWG7ArF1Iz1zmmKJEdtxBVRCw3JJhMsEy5EGWpAWwMA==";

    /**
     * RSA密钥对对象
     */
    public static class RsaKeyPair{
        private final String publicKey;
        private final String privateKey;

        public RsaKeyPair(String publicKey, String privateKey){
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }
    }

    /**
     * 构建RSA密钥对
     *
     * @return 生成后的公私钥信息
     * @throws NoSuchAlgorithmException
     */
    public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey puk = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey prk = (RSAPrivateKey) keyPair.getPrivate();
        String pukStr = Base64.encodeBase64String(puk.getEncoded());
        String prkStr = Base64.encodeBase64String(prk.getEncoded());
        return new RsaKeyPair(pukStr, prkStr);
    }

    /**
     * 公钥加密
     *
     * @param publicKeyString 公钥
     * @param text 待加密的文本
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String publicKeyString, String text) throws Exception
    {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 公钥解密
     *
     * @param publicKeyString 公钥
     * @param text 待解密的信息
     * @return 解密后的文本
     */
    public static String decryptByPublicKey(String publicKeyString, String text) throws Exception
    {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥加密
     *
     * @param privateKeyString 私钥
     * @param text 待加密的信息
     * @return 加密后的文本
     */
    public static String encryptByPrivateKey(String privateKeyString, String text) throws Exception
    {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

    /**
     * 私钥解密
     *
     * @param privateKeyString 私钥
     * @param text 待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception
    {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

    /**
     * 私钥解密
     *
     * @param text 私钥
     * @param text 待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String text) throws Exception
    {
        return decryptByPrivateKey(privateKey, text);
    }

    public static void main(String[] args) throws Exception {
        RsaKeyPair rsaKeyPair = null;
        System.out.println("公钥：");
        System.out.println(publicKey);
        System.out.println("私钥：");
        System.out.println(privateKey);
        String phone = "4008123123";
        //公钥加密，私钥解密
        String phoneRsa = encryptByPublicKey(publicKey, phone);
        System.out.println("加密后："+phoneRsa);
        String phoneRsa2 = decryptByPrivateKey(privateKey, phoneRsa);
        System.out.println("解密后："+phoneRsa2);
        //私钥加密，公钥解密
        String phoneRsa3 = encryptByPrivateKey(privateKey, phone);
        System.out.println("加密后："+phoneRsa3);
        String phoneRsa4 = decryptByPublicKey(publicKey, phoneRsa3);
        System.out.println("解密后："+phoneRsa4);
    }

}